package cc.sunni.user.service.impl;

import cc.sunni.api.utils.PageUtils;
import cc.sunni.api.utils.Query;
import cc.sunni.common.enums.Sex;
import cc.sunni.common.enums.UserStatus;
import cc.sunni.common.exception.RRException;
import cc.sunni.common.utils.DesensitizationUtil;
import cc.sunni.common.utils.RedisOperator;
import cc.sunni.common.utils.ResultEnum;
import cc.sunni.pojo.bo.UpdateUserInfoBO;
import cc.sunni.pojo.user.AppUser;
import cc.sunni.pojo.vo.PublisherVO;
import cc.sunni.user.mapper.AppUserDao;
import cc.sunni.user.service.AppUserService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("appUserService")
public class AppUserServiceImpl extends ServiceImpl<AppUserDao, AppUser> implements AppUserService {
    @Autowired
    public RedisOperator redis;

    public static final String REDIS_USER_INFO = "redis_user_info";
    private static final String USER_FACE0 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxFw_8_qAIlFXAAAcIhVPdSg994.png";
    private static final String USER_FACE1 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxF6ZUySASMbOAABBAXhjY0Y649.png";
    private static final String USER_FACE2 = "http://122.152.205.72:88/group1/M00/00/05/CpoxxF6ZUx6ANoEMAABTntpyjOo395.png";

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AppUser> page = this.page(
                new Query<AppUser>().getPage(params),
                // 拼接查询条件
                new LambdaQueryWrapper<AppUser>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public AppUser createUser(String mobile) {
        /**
         * 互联网项目都要考虑可扩展性
         * 如果未来的业务激增，那么就需要分库分表
         * 那么数据库表主键id必须保证全局（全库）唯一，不得重复
         */
        AppUser user = new AppUser();
        user.setMobile(mobile);
        user.setNickname("用户：" + DesensitizationUtil.commonDisplay(mobile));
        user.setFace(USER_FACE0);
        user.setBirthday(new Date());
        user.setSex(Sex.secret.type);
        user.setActiveStatus(UserStatus.INACTIVE.type);
        user.setTotalIncome(0);
        user.setCreatedTime(new Date());
        user.setUpdatedTime(new Date());
        baseMapper.insert(user);
        return user;
    }

    @Override
    public AppUser getUserByUserId(String userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public void updateUserInfo(UpdateUserInfoBO updateUserInfoBO) {
        String userId = updateUserInfoBO.getId();
        // 保证双写一致，先删除redis中的数据，后更新数据库
        redis.del(REDIS_USER_INFO + ":" + userId);

        AppUser userInfo = new AppUser();
        BeanUtils.copyProperties(updateUserInfoBO, userInfo);
        userInfo.setUpdatedTime(new Date());
        userInfo.setActiveStatus(UserStatus.ACTIVE.type);

        int result = baseMapper.updateById(userInfo);
        if (result != 1) {
            throw new RRException(ResultEnum.USER_UPDATE_ERROR);
        }

        // 缓存双删策略
        try {
            Thread.sleep(10);
            redis.del(REDIS_USER_INFO + ":" + userId);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<PublisherVO> getUserList(List<String> userIdList) {
        return null;
    }

}